package com.robotlab.easytranslate.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.support.v7.widget.Toolbar;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.robotlab.easytranslate.R;
import com.robotlab.easytranslate.fragment.AboutFragment;
import com.robotlab.easytranslate.fragment.BookFragment;
import com.robotlab.easytranslate.fragment.OcrFragment;
import com.robotlab.easytranslate.fragment.SettingFragment;
import com.robotlab.easytranslate.fragment.TranslateFragment;
import com.robotlab.easytranslate.service.RecognizeService;
import com.robotlab.easytranslate.util.FileUtil;
import com.robotlab.easytranslate.util.HttpUtil;
import com.robotlab.easytranslate.util.InputMethodUtils;
import com.robotlab.easytranslate.util.PicUtil;

import org.litepal.LitePal;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.robotlab.easytranslate.MyApplication.getContext;

public class MainActivity extends AppCompatActivity implements BookFragment.sendWord{

    private static final int REQUEST_CODE_GENERAL_BASIC = 106;
    private AlertDialog.Builder alertDialog;
    private Drawer result;
    private Toolbar toolbar;
    private Drawable drawable;
    public static TranslateFragment translateFragment;
    public String data="";
    public Context context;
    public Drawer getResult(){
        return result;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context =this;
        setContentView(R.layout.activity_main);
        initView();
        initToolbar();
        loadOnePic();
        initDrawer();
        getDataFromOutSide();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            OCR.getInstance(this).release();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //result.setSelection(1,true);
        getDataFromOutSide();
    }

    private void getDataFromOutSide() {
        Intent intent = getIntent();
        data = intent.getStringExtra("input_text");
        if (data != null) {
            if (!data.equals("")) {
                result.setSelection(1, true);
                intent.putExtra("input_text", "");
            }
            //data = null;
        }
    }


    private void initView() {
        translateFragment = new TranslateFragment();
        alertDialog = new AlertDialog.Builder(getContext());
        ChangeFragment(1);
    }

    private void initDrawer() {
        AccountHeader headerResult = new AccountHeaderBuilder().
                withActivity(this).
                withHeaderBackground(drawable).
                build();
        PrimaryDrawerItem translateItem = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.drawer_item_translate).withIcon(R.mipmap.translate);
        PrimaryDrawerItem ocrItem = new PrimaryDrawerItem().withIdentifier(2).withName(R.string.drawer_item_ocr).withIcon(R.mipmap.ocr);
        PrimaryDrawerItem bookItem = new PrimaryDrawerItem().withIdentifier(3).withName(R.string.drawer_item_book).withIcon(R.mipmap.book);
        PrimaryDrawerItem settingItem = new PrimaryDrawerItem().withIdentifier(5).withName(R.string.drawer_item_settings).withIcon(R.mipmap.setting);
        PrimaryDrawerItem aboutItem = new PrimaryDrawerItem().withIdentifier(6).withName(R.string.drawer_item_about).withIcon(R.mipmap.about);
        result = new DrawerBuilder().
                withActivity(this).
                addDrawerItems(
                        translateItem,
                        ocrItem,
                        bookItem,
                        new DividerDrawerItem(),
                        settingItem,
                        aboutItem
                ).
                withAccountHeader(headerResult).
                withToolbar(toolbar).
                withOnDrawerItemClickListener(listener).
                build();

    }

    private Drawer.OnDrawerItemClickListener listener = new Drawer.OnDrawerItemClickListener() {
        @Override
        public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
            switch (position) {
                case 1:
                    ChangeFragment(1);
                    toolbar.setTitle(R.string.app_name);
                    result.closeDrawer();
                    break;
                case 2:
                    ChangeFragment(2);
                    toolbar.setTitle(R.string.drawer_item_ocr);
                    result.closeDrawer();
                    break;
                case 6:
                    ChangeFragment(3);
                    toolbar.setTitle(R.string.drawer_item_about);
                    result.closeDrawer();
                    break;
                case 5:
                    ChangeFragment(4);
                    toolbar.setTitle(R.string.drawer_item_settings);
                    result.closeDrawer();
                    break;
                case 3:
                    ChangeFragment(5);
                    toolbar.setTitle(R.string.drawer_item_book);
                    result.closeDrawer();
                    break;
            }
            return true;
        }
    };

    private void initToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    private void ChangeFragment(int position) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragment = null;
        if (position == 1) {
            fragment = translateFragment;
        } else if (position == 2) {
            fragment = new OcrFragment();
        } else if (position == 3) {
            fragment = new AboutFragment();
        } else if (position == 4) {
            fragment = new SettingFragment();
        } else if (position == 5) {
            fragment = new BookFragment();
        }
        transaction.replace(R.id.content_frame, fragment);
        transaction.commit();
    }

    private void loadOnePic() {
        String picUrl = "http://open.iciba.com/dsapi";
        HttpUtil.sendOkHttpRequest(picUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final String onePic = PicUtil.handleOnePicResponse(responseText);
                Log.d("varenyzc", onePic);
                //drawable = loadImageFromNetWork(onePic);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //Glide.with(MainActivity.this).load(onePic).into(imageView);
                        Glide.with(MainActivity.this).load(onePic).asBitmap().into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                drawable = new BitmapDrawable(getResources(),resource);
                                initDrawer();
                            }
                        });
                    }
                });
            }
        });
    }

    @Override
    public void sendWord(String word) {
        translateFragment.setWord(word);
        //Toast.makeText(MainActivity.this, translateFragment.getInput().getText(), Toast.LENGTH_SHORT).show();
    }

}
